<template>
  <div class="search-suggestion">
    <van-cell 
     icon="search" 
     v-for="(item,index) in suggestions" 
     :key='index' 
     @click="$emit('search',item)">
      <div slot="title" v-html="highlight(item)"></div>
     </van-cell>
  
  </div>
</template>

<script>
import {gesearch} from '@/api/search'
import {debounce} from 'lodash'
export default {
  name: "searchSuggestion",
  data() {
    return {
      suggestions:[] //联想数据建议列表
    }
  },
  props:{
    searchText: {
        type: String,
        required:true
        
    } 
  },
  watch:{
    searchText:{   //输入框的值
        //当searchText 发生改变的时候就会调用 handler 函数
        //注意：handler 函数名称是固定的
        //debounce 第一个参数是函数 第二个参数是延时时间  处理防抖
        handler: debounce(function(value){
              this.loadSearchSuggestions(value)
        },300) ,
        // handler(value){
        //     this.loadSearchSuggestions(value)

        // },
        immediate:true //该回调会在侦听开始之后被立即调用
    }
  },
  methods:{
    async loadSearchSuggestions( q ){
        try{    
           const {data} = await gesearch(q)
           this.suggestions = data.data.options
           
           console.log(data);
        }catch(err){
         this.$toast('数据获取失败，请稍后再试')
    
        }

    },
    highlight(item){
      const highlightStr = `<span class = "active">${this.searchText}</span>`
      
      const rag = new RegExp(this.searchText ,'gi')
      return item.replace(rag,highlightStr)
    }

  }
  
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ span.active{
    color: #3296fa;
  }
}
</style>